<template>
   <el-card class="userAvatar-container">
     <!-- 面板屑导航 -->
    <el-breadcrumb separator="/" style="margin-bottom: 40px">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>个人中心</el-breadcrumb-item>
      <el-breadcrumb-item>更换头像</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 用来展示头像的盒子 -->
    <div class="avatar-box">
      <img :src="defaultImg" />
    </div>
    <div>
      <el-button type="primary" class="el-icon-plus" @click="$refs.fileRef.click()">选择图片</el-button>
      <el-button type="success" class="el-icon-upload" :disabled="isDisabled" @click="handleSubmit">上传头像</el-button>
      <input type="file" ref="fileRef" @change="changeAvatar" hidden>
    </div>
  </el-card>
</template>

<script>
import defaultImg from '@/assets/images/avatar.jpg'

import { reqUpdateAvatar } from '@/api/user'
export default {
  name: 'UserAvatar',
  data () {
    return {
      defaultImg: defaultImg, // 默认封面
      isDisabled: true // 上传按钮的禁用和启用
    }
  },
  methods: {
    // 头像本地展示
    changeAvatar (e) {
      const file = e.target.files[0]
      if (file) {
        // 1. 创建文件读取对象
        const fd = new FileReader()
        // 2. 读文件
        fd.readAsDataURL(file)
        // 3. 取结果 base64
        fd.onload = () => {
          this.defaultImg = fd.result
          this.isDisabled = false // 上传成功后启用上传按钮
        }
      }
    },
    // 上传头像发送请求
    async handleSubmit () {
      // 1. 发送请求
      const { data } = await reqUpdateAvatar(this.defaultImg)
      //  2. 提示
      this.$message.success(data.message)
      // 3. 重新获取个人信息更新展示图像的位置
      this.$store.dispatch('user/getUserInfo')
    }
  }

}
</script>

<style lang="less" scoped>
.userAvatar-container {
  padding: 0 0 20px 20px;

  .avatar-box {
    img {
      width: 350px;
      height: 350px;
      object-fit: cover;
    }
  }

  .btns {
    padding-top: 10px;
  }
}
</style>
